import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { CheeseToastService } from './toast.service';
import { ToastItem, ToastOptions } from './toast.model';
import { trigger, state, style, transition, animate } from '@angular/animations';

@Component({
  selector: 'ns-toast-container',
  templateUrl: './toast.component.html',
  styleUrls: ['./toast.component.css'],
  animations: [
    trigger('toastAnimation', [
      state('void', style({
        opacity: 0,
        transform: 'translateY(-20px)'
      })),
      state('visible', style({
        opacity: 1,
        transform: 'translateY(0)'
      })),
      transition('void => visible', animate('200ms ease-out')),
      transition('visible => void', animate('200ms ease-in'))
    ])
  ]
})
export class CheeseToastComponent implements OnInit, OnDestroy {
  toasts: { [key: string]: ToastItem[] } = {
    'top-center': [],
    'top-right': [],
    'bottom-center': [],
    'bottom-right': []
  };
  
  private subscription: Subscription = new Subscription();

  constructor(private toastService: CheeseToastService) {}

  ngOnInit(): void {
    this.subscription.add(
      this.toastService.toasts$.subscribe(toasts => {
        // 按位置分组
        this.toasts = {
          'top-center': [],
          'top-right': [],
          'bottom-center': [],
          'bottom-right': []
        };
        
        toasts.forEach(toast => {
          const position = toast.position || 'top-center';
          if (!this.toasts[position]) {
            this.toasts[position] = [];
          }
          this.toasts[position].push(toast);
        });
      })
    );
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }

  closeToast(id: string): void {
    this.toastService.remove(id);
  }

  getToastIcon(type: string | undefined): string {
    switch (type) {
      case 'success':
        return '✓';
      case 'error':
        return '✗';
      case 'warning':
        return '⚠';
      case 'info':
      default:
        return 'ℹ';
    }
  }

  getPositionClass(position: string): string {
    return `toast-container-${position}`;
  }
}